package rpc;

import com.aruba.utils.RBConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;
import java.util.UUID;

public class Publisher {

    public static final String QUEUE_PUB = "topic-publisher";
    public static final String QUEUE_CON = "topic-consumer";

    @Test
    public void publisher() throws Exception {
        //1. 获取连接对象
        Connection connection = RBConnectionUtil.getConnection();

        //2. 创建信道
        Channel channel = connection.createChannel();

        //3. 构建队列  参数：队列名 是否持久化 是否排外（只允许一个消费者） 长时间未使用是否自动删除 其他参数
        channel.queueDeclare(QUEUE_PUB, false, false, false, null);
        channel.queueDeclare(QUEUE_CON, false, false, false, null);

        //4. 监听消费者发送消息
        channel.basicConsume(QUEUE_CON, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者发送的消息：" + new String(body, "UTF-8"));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });

        //5. 发送消息
        // 构建额外的信息
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .replyTo(QUEUE_CON)
                .correlationId(UUID.randomUUID().toString())
                .build();
        //参数： 交换机 routing-Key 消息其他参数  消息
        channel.basicPublish("", QUEUE_PUB, props, "hi consumer".getBytes());

        System.in.read();
    }

}
